package com.linewell.system.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.linewell.commom.controller.BackendBaseController;
import com.linewell.system.model.SysUsers;
import com.linewell.system.pagemodel.DataGrid;
import com.linewell.system.pagemodel.PageHelper;
import com.linewell.system.pagemodel.ReturnInfo;
import com.linewell.system.service.ISysUsersService;
import com.linewell.system.utils.ConfigProperty;
import com.linewell.system.utils.FileUploadUtil;
import com.linewell.system.utils.MD5;

/**
 * 系统用户控制器
 */
@Controller
@RequestMapping("/manage/sysUsers")
public class SysUsersController extends BackendBaseController {
		
		private static final Log log = LogFactory.getLog(SysUsersController.class);
		@Autowired
		private ISysUsersService sysUsersService;
		/**
		 * 跳转至 sys_user页
		 */
		@RequestMapping(value = "/index")
		public String index(HttpServletRequest request) {
			return super.index("/WEB-INF/pages/system/sys_users/sys_users_list.jsp", request);
		}		
		/**
		 * 数据查询
		 */
		@ResponseBody
		@RequestMapping(value = "/dataGrid")
		public DataGrid dataGrid(@ModelAttribute SysUsers u,PageHelper ph,HttpServletRequest request) {
			ph.setSort("userId");
			ph.setOrder("desc");
			DataGrid dg = sysUsersService.datagrid(ph,u,getUserDepId(request));
			return dg;
		}
		
		/**
		 * 添加
		 */
		@RequestMapping(value = "/add")
		public String add(Map<String, Object> map) {
			map.put("saveUrl", "/manage/sysUsers/addSave");
			return "/WEB-INF/pages/system/sys_users/sys_users_au.jsp";
		}
		
		/**
		 * 添加保存
		 */
		@ResponseBody
		@RequestMapping(value = "/addSave")
		public ReturnInfo addSave(String password,@Valid SysUsers sysUsers, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
			if (b.getErrorCount() > 0) { // 数据校验
				for (FieldError error : b.getFieldErrors()) {
					log.info(error.getField() + ":" + error.getDefaultMessage());
					result.setMsg(error.getField() + "" + error.getDefaultMessage());
				}
				result.setSuccess(1);
			} else {
				if(password != null){
					password=MD5.md5(password);
				}else{
					password=MD5.md5("123456");
				}
				if (sysUsers != null) {
					if(file != null){
						try {
							String icon_url = FileUploadUtil.saveFile(file, request, ConfigProperty.getProperty("fileUplaodPath", "config") + "photo");
							sysUsers.setPhoto(icon_url);
						} catch (Exception e) {
							log.info("上传异常"+e.getMessage());
						}
					}
					try {
						sysUsers.setPassword(password);
						sysUsersService.save(sysUsers);
					} catch (Exception e) {
						result.setMsg("保存失败！");
						if(sysUsers.getSysDepartment().getDepId() == 0){
							result.setMsg("请选择部门！");
						}
						result.setSuccess(1);
					}
				}
			}
			return result;
		}

		/**
		 * 修改
		 */
		@RequestMapping(value = "/edit")
		public String edit(String id, Map<String, Object> map) {
			log.info(id);
			map.put("saveUrl", "/manage/sysUsers/editSave");
			if (id != null) {
				List<SysUsers> model = sysUsersService.getUser(id);
				map.put("model", model.get(0));
			}
			return "/WEB-INF/pages/system/sys_users/sys_users_au.jsp";
		}
		
		/**
		 * 修改保存
		 */
		@ResponseBody
		@RequestMapping(value = "/editSave")
		public ReturnInfo editSave(@Valid SysUsers sysUsers, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
			if (b.getErrorCount() > 0) { // 数据校验
				log.info("数据校验出错！");
				for (FieldError error : b.getFieldErrors()) {
					log.info(error.getField() + ":" + error.getDefaultMessage());
					result.setMsg(error.getField() + "" + error.getDefaultMessage());
				}
				result.setSuccess(1);
			} else {
				if (sysUsers != null) {
					if(file != null){
						try {
							String icon_url = FileUploadUtil.saveFile(file, request, getConfigAttr("fileUplaodPath") + "photo");
							sysUsers.setPhoto(icon_url);
						} catch (Exception e) {
							log.info("上传异常"+e.getMessage());
						}
					}
					try {
						sysUsersService.update(sysUsers);
					} catch (Exception e) {
						log.info("修改异常" + e.getMessage());
						result.setMsg("修改失败");
						if(sysUsers.getSysDepartment().getDepId() == null){
							result.setMsg("请选择部门！");
						}
						result.setSuccess(1);
					}

				}
			}

			return result;
		}

		/**
		 * 删除（物理删除）
		 */
		@ResponseBody
		@RequestMapping(value = "/delete")
		public ReturnInfo delete(String ids, ReturnInfo result) {
			if (ids != null) {
				try {
					sysUsersService.deleteAll(ids);
				} catch (Exception e) {
					log.info("删除异常" + e.getMessage());
					result.setMsg("删除失败！");
					result.setSuccess(1);
				}
			}

			return result;
		}

		/**
		 * 移除（逻辑删除），将状态修改为0
		 */
		@ResponseBody
		@RequestMapping(value = "/remove")
		public ReturnInfo remove(String ids, ReturnInfo result) {
			log.info(ids);
			if (ids != null) {
				try {
					sysUsersService.removeAll(ids);
				} catch (Exception e) {
					log.info("移除异常" + e.getMessage());
					result.setMsg("移除失败！");
					result.setSuccess(1);
				}
			}

			return result;
		}
		
		public String getConfigAttr(String str) {
			String attrStr = null;
			Properties prop = new Properties();
			InputStream is = this.getClass().getResourceAsStream("/config.properties");
			try {
				prop.load(is);
				attrStr = prop.getProperty(str);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return attrStr;
		}
}
